package com.feature.core.util;

import org.apache.commons.lang3.StringUtils;

import com.feature.core.constant.SecurityConstants;

import jakarta.servlet.http.HttpServletRequest;

public class WebUtil {
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader(SecurityConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotBlank(token) && token.startsWith(SecurityConstants.PREFIX)) {
            token = token.replaceFirst(SecurityConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    /**
     * 是否外部请求
     * 
     * @param request
     * @return
     * @author wangzhiyue
     * @date 2024/12/10 17:14:23
     */
    public static boolean isOuterRequest(HttpServletRequest request) {
        String fromSource = request.getHeader(SecurityConstants.FROM_SOURCE_REQUEST_HEAD);
        return SecurityConstants.FROM_SOURCE_OUTER.equals(fromSource);
    }
}
